package com.nimlib.adapter;

import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.jinlejia.erp.R;
import com.jinlejia.erp.databinding.AdapterImMsgInHouseInfoBinding;
import com.jinlejia.erp.databinding.AdapterImMsgInImgBinding;
import com.jinlejia.erp.databinding.AdapterImMsgInTextBinding;
import com.jinlejia.erp.databinding.AdapterImMsgOutHouseInfoBinding;
import com.jinlejia.erp.databinding.AdapterImMsgOutImgBinding;
import com.jinlejia.erp.databinding.AdapterImMsgOutTextBinding;
import com.jinlejia.erp.databinding.AdapterImTopHouseInfoBinding;
import com.lab.Lab;
import com.netease.nimlib.sdk.msg.attachment.ImageAttachment;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.constant.AttachStatusEnum;
import com.netease.nimlib.sdk.msg.constant.MsgDirectionEnum;
import com.netease.nimlib.sdk.msg.constant.MsgStatusEnum;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.nos.model.NosThumbParam;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;
import com.nimlib.ImageViewBean;
import com.nimlib.emoji.MoonUtil;
import com.nimlib.msg.HouseInfoMessage;
import com.nimlib.msg.LocalHouseInfoMessage;
import com.nimlib.utils.NimIMUtils;
import com.nimlib.utils.NimUserInfoCache;
import com.nimlib.utils.ScreenUtil;
import com.weight.CircleImageView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class IMChartListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final int TYPE_IN_TEXT = 1; //自己发送的文本消息
    private final int TYPE_OUT_TEXT = 2; //他人发送的文本消息

    private final int TYPE_IN_IMG = 3; //自己发送的图片消息
    private final int TYPE_OUT_IMG = 4; //他人发送的图片消息

    private final int TYPE_IN_HOUSE_INFO = 5; //自己发送的房源信息
    private final int TYPE_OUT_HOUSE_INFO = 6; //他人发送的房源信息

    private final int TYPE_TOP_HOUSE_INFO = 7; //房源信息

    private final int TYPE_LOAD = 10; //加载中
    private List<IMMessage> items;
    private NimUserInfo localUser;
    private Context mContext;
    public IMChartListAdapter(Context context,NimUserInfo localUser,List<IMMessage> data){
        this.mContext = context;
        this.items = data;
        this.localUser = localUser;
    }


    public void setData(List<IMMessage> data){
        this.items = data;
    }

    public void addData(List<IMMessage> data){
        this.items.addAll(data);
        notifyDataSetChanged();
    }

    public List<IMMessage> getMessageItem() {
        return items;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        RecyclerView.ViewHolder holder = new LoadHolder(inflater.inflate(R.layout.adapter_im_empty_layout,parent,false));
        if (viewType== TYPE_IN_TEXT){
            holder = new TextInHolder(inflater.inflate(R.layout.adapter_im_msg_in_text,parent,false));
        }else if (viewType == TYPE_OUT_TEXT){
            holder = new TextOutHolder(inflater.inflate(R.layout.adapter_im_msg_out_text,parent,false));
        }else if (viewType == TYPE_IN_IMG){
            holder = new ImageInHolder(inflater.inflate(R.layout.adapter_im_msg_in_img,parent,false));
        }else if (viewType==TYPE_OUT_IMG){
            holder = new ImageOutHolder(inflater.inflate(R.layout.adapter_im_msg_out_img,parent,false));
        }else if (viewType == TYPE_IN_HOUSE_INFO){
            holder = new HouseInfoInHolder(inflater.inflate(R.layout.adapter_im_msg_in_house_info,parent,false));
        }else if (viewType == TYPE_OUT_HOUSE_INFO){
            holder = new HouseInfoOutHolder(inflater.inflate(R.layout.adapter_im_msg_out_house_info,parent,false));
        }else if (viewType == TYPE_TOP_HOUSE_INFO){
            holder = new ChartHouseInfoHolder(inflater.inflate(R.layout.adapter_im_top_house_info,parent,false));
        }
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ChartHouseInfoHolder){
            bindChartHouseInfoHolder((ChartHouseInfoHolder) holder,position);
            return;
        }
        if (holder instanceof TextInHolder){
            bindTextInHolder((TextInHolder) holder,position);
        }else if (holder instanceof TextOutHolder){
            bindTextOutHolder((TextOutHolder) holder,position);
        }else if (holder instanceof ImageInHolder){
            bindImageInHolder((ImageInHolder) holder,position);
        }else if (holder instanceof ImageOutHolder){
            bindImageOutHolder((ImageOutHolder) holder,position);
        }else if (holder instanceof HouseInfoInHolder){
            bindHouseInfoInHolder((HouseInfoInHolder) holder,position);
        }else if (holder instanceof HouseInfoOutHolder){
            bindHouseInfoOutHolder((HouseInfoOutHolder) holder,position);
        }
    }

    @Override
    public int getItemCount() {
        if (items==null){
            return 1;
        }
        return items.size();
    }

    //region 显示时间
    private final long timeSpace = TimeUnit.MINUTES.toMillis(5); //显示时间发言的间隔 (5分钟)
    private SparseArray<Long> cacheShowTime;

    private void showTime(int position,TextView textView){
        if (cacheShowTime ==null){
            cacheShowTime = new SparseArray<>();
            long lastTime = 0;
            for (int i = 0; i < items.size(); i++) { //如果当前消息时间，大于显示间隔时间，则显示
                long time = items.get(i).getTime();
                long space = time-lastTime;
                if (space>=timeSpace){
                    cacheShowTime.put(i,time);
                    lastTime = time;
                    Lab.log(i+"=="+formatTime(time)+"=="+space);
                }
            }
        }
        long cacheTime = cacheShowTime.get(position,-1L);
        if (cacheTime==-1L){ //如果没有进行缓存，则直接不显示
            textView.setVisibility(View.GONE);
            textView.setText(null);
        }else { //如果已经进行了缓存，则显示缓存的时间
            textView.setVisibility(View.VISIBLE);
            textView.setText(formatTime(cacheTime));
        }
    }

    private String formatTime(long time){
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        String format="%s月%s日 %s:%s";
        String monthStr = String.valueOf(calendar.get(Calendar.MONTH)+1);
        int date = calendar.get(Calendar.DATE);
        String dateStr = String.valueOf(date);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        String hourStr;
        if (hour>=10){
            hourStr=String.valueOf(hour);
        }else {
            hourStr= "0" + hour;
        }
        int minute = calendar.get(Calendar.MINUTE);
        String minuteStr;
        if (minute>=10){
            minuteStr = String.valueOf(minute);
        }else {
            minuteStr = "0"+minute;
        }
        return String.format(Locale.CHINA,format,monthStr,dateStr,hourStr,minuteStr);
    }
    //endregion

    @Override
    public int getItemViewType(int position) {
        IMMessage message = items.get(position);
        if (message.getMsgType()==MsgTypeEnum.custom && message.getAttachment()!=null){
            MsgAttachment attachment = message.getAttachment();
            if (attachment instanceof LocalHouseInfoMessage){
                return TYPE_TOP_HOUSE_INFO;
            }
        }
        if (message.getMsgType() == MsgTypeEnum.text){ //文本消息
            if (message.getDirect()== MsgDirectionEnum.Out){
                return TYPE_OUT_TEXT;
            }else if (message.getDirect()== MsgDirectionEnum.In){
                return TYPE_IN_TEXT;
            }
        }else if (message.getMsgType()==MsgTypeEnum.image){ //图片消息
            if (message.getDirect() == MsgDirectionEnum.Out){
                return TYPE_OUT_IMG;
            }else if (message.getDirect()== MsgDirectionEnum.In){
                return TYPE_IN_IMG;
            }
        }else if (message.getMsgType()==MsgTypeEnum.custom &&
                !TextUtils.isEmpty(message.getAttachStr())){ //自定义消息
            String attachStr = message.getAttachStr();
            JSONObject attachJson = JSON.parseObject(attachStr);
            int type = attachJson.getIntValue("type");
            if (type==HouseInfoMessage.TYPE){ //如果是房源消息
                if (message.getDirect()==MsgDirectionEnum.Out ){
                    return TYPE_OUT_HOUSE_INFO;
                }else if (message.getDirect()==MsgDirectionEnum.In){
                    return TYPE_IN_HOUSE_INFO;
                }
            }
        }
        return TYPE_LOAD;
    }

    //region 接收的文本
    class TextInHolder extends RecyclerView.ViewHolder{

        TextInHolder(@NonNull View itemView) {
            super(itemView);
            DataBindingUtil.bind(itemView);
        }
    }

    private void bindTextInHolder(TextInHolder holder,int position){
        IMMessage message = items.get(position);
        baseMessageView(message);
        AdapterImMsgInTextBinding binding = DataBindingUtil.getBinding(holder.itemView);
        String fromAccount = message.getFromAccount();
        NimUserInfo info = NimUserInfoCache.getInstance().getUserInfo(fromAccount);
        if (info!=null){
            loadUserHeader(info.getAvatar(),binding.imageView);
        }
        userHeaderInEvent(binding.imageView);
        MoonUtil.identifyFaceExpression(mContext, binding.contentTextView, message.getContent(), ImageSpan.ALIGN_BOTTOM);

        showTime(position,binding.msgTimeTextView);
    }
    //endregion

    //region 发出的文本
    class TextOutHolder extends RecyclerView.ViewHolder{

        TextOutHolder(@NonNull View itemView) {
            super(itemView);
            DataBindingUtil.bind(itemView);
        }
    }

    private void bindTextOutHolder(TextOutHolder holder,int position){
        AdapterImMsgOutTextBinding binding = DataBindingUtil.getBinding(holder.itemView);
        loadUserHeader(localUser.getAvatar(),binding.imageView);
        IMMessage message = items.get(position);
        baseMessageView(message);
        MoonUtil.identifyFaceExpression(mContext, binding.contentTextView, message.getContent(), ImageSpan.ALIGN_BOTTOM);
        showTime(position,binding.msgTimeTextView);

    }
    //endregion

    //region 接收的图片
    class ImageInHolder extends RecyclerView.ViewHolder{

        ImageInHolder(@NonNull View itemView) {
            super(itemView);
            DataBindingUtil.bind(itemView);
        }
    }

    private void bindImageInHolder(ImageInHolder holder,int position){
        IMMessage message = items.get(position);
        baseMessageView(message);
        AdapterImMsgInImgBinding binding = DataBindingUtil.getBinding(holder.itemView);
        ImageAttachment image = (ImageAttachment) message.getAttachment();
        String path = getPicThumbPath(image);
        String fromAccount = message.getFromAccount();
        NimUserInfo info = NimUserInfoCache.getInstance().getUserInfo(fromAccount);
        if (info!=null){
            loadUserHeader(info.getAvatar(),binding.imageView);
        }
        userHeaderInEvent(binding.imageView);

        loadImage(path,binding.thumbImageView);
        ViewGroup.LayoutParams params = binding.thumbImageView.getLayoutParams();
        params.width = getImageMaxEdge();
        params.height = getImageMaxEdge();
        binding.thumbImageView.setLayoutParams(params);
        refreshStatus(message,binding.messageItemAlert,binding.progressLayout,binding.progressText);
        if (adapterEvent!=null){
            String viewPath = TextUtils.isEmpty(image.getPath())?image.getThumbPath():image.getPath();
            ImageViewBean curBean = new ImageViewBean();
            curBean.setPosition(position);
            curBean.setUuid(message.getUuid());
            curBean.setUrl(viewPath);

            if (adapterEvent!=null){
                binding.thumbImageView.setOnClickListener(v-> {
                    ArrayList<ImageViewBean> pics = new ArrayList<>();
                    for (int i = 0; i < items.size(); i++) {
                        IMMessage m = items.get(i);
                        if (m.getAttachment() instanceof ImageAttachment){
                            ImageAttachment pic = (ImageAttachment) m.getAttachment();
                            String path_ = getPicViewPath(pic);
                            ImageViewBean bean = new ImageViewBean();
                            bean.setPathForSave(pic.getPathForSave());
                            bean.setHeight(pic.getHeight());
                            bean.setWidth(pic.getWidth());
                            bean.setUrl(path_);
                            bean.setUuid(m.getUuid());
                            bean.setPosition(i);
                            pics.add(bean);
                        }
                    }
                    int viewPosition = pics.indexOf(curBean);
                    NosThumbParam thurm = new NosThumbParam();
                    thurm.width = image.getWidth();
                    thurm.height = image.getHeight();
                    adapterEvent.onClickPictureItem(pics,viewPosition);
                });
            }
        }
        showTime(position,binding.msgTimeTextView);
    }

    //endregion

    private String getPicThumbPath(ImageAttachment imageAttachment){
        String path = "";
        String thumbPath = imageAttachment.getThumbPath();
        if (!TextUtils.isEmpty(thumbPath)){
            path = thumbPath;
        }else if (!TextUtils.isEmpty(imageAttachment.getPath())){
            path = imageAttachment.getPath();
        }
        if (TextUtils.isEmpty(path)){
            path = imageAttachment.getUrl();
        }
        return path;
    }


    private String getPicViewPath(ImageAttachment imageAttachment){
        String path = imageAttachment.getPath();
        if (path==null){
            path = imageAttachment.getUrl();
        }
        return path;
    }

    //region 发出的图片
    class ImageOutHolder extends RecyclerView.ViewHolder{

        ImageOutHolder(@NonNull View itemView) {
            super(itemView);
            DataBindingUtil.bind(itemView);
        }
    }
    private void bindImageOutHolder(ImageOutHolder holder,int position){
        IMMessage message = items.get(position);
        baseMessageView(message);
        AdapterImMsgOutImgBinding binding = DataBindingUtil.getBinding(holder.itemView);
        ImageAttachment image = (ImageAttachment) message.getAttachment();
        String path = getPicThumbPath(image);
        loadUserHeader(localUser.getAvatar(),binding.imageView);
        loadImage(path,binding.thumbImageView);
        ViewGroup.LayoutParams params = binding.thumbImageView.getLayoutParams();
        params.width = getImageMaxEdge();
        params.height = getImageMaxEdge();
        binding.thumbImageView.setLayoutParams(params);
        refreshStatus(message,binding.messageItemAlert,binding.progressLayout,binding.progressText);
        if (adapterEvent!=null){
            String viewPath = TextUtils.isEmpty(image.getPath())?image.getThumbPath():image.getPath();
            ImageViewBean curBean = new ImageViewBean();
            curBean.setPosition(position);
            curBean.setUuid(message.getUuid());
            curBean.setUrl(viewPath);
            if (adapterEvent!=null){
                binding.thumbImageView.setOnClickListener(v-> {
                    ArrayList<ImageViewBean> pics = new ArrayList<>();
                    for (int i = 0; i < items.size(); i++) {
                        IMMessage m = items.get(i);
                        if (m.getAttachment() instanceof ImageAttachment){
                            ImageAttachment pic = (ImageAttachment) m.getAttachment();
                            String path_ = getPicViewPath(pic);
                            ImageViewBean bean = new ImageViewBean();
                            bean.setPathForSave(pic.getPathForSave());
                            bean.setHeight(pic.getHeight());
                            bean.setWidth(pic.getWidth());
                            bean.setUrl(path_);
                            bean.setUuid(m.getUuid());
                            bean.setPosition(i);
                            pics.add(bean);
                        }
                    }
                    int viewPosition = pics.indexOf(curBean);
                    adapterEvent.onClickPictureItem(pics,viewPosition);
                });
            }
        }
        showTime(position,binding.msgTimeTextView);
    }

    private static int getImageMaxEdge() {
        return (int) (165.0 / 320.0 * ScreenUtil.screenWidth);
    }

    private static int getImageMinEdge() {
        return (int) (76.0 / 320.0 * ScreenUtil.screenWidth);
    }


    private Map<String, Float> progresses = new HashMap<>(); // 有文件传输，需要显示进度条的消息ID map
    private void refreshStatus(IMMessage message, ImageView imageView, ViewGroup progressLayout, TextView progressText){
        ImageAttachment attachment = (ImageAttachment) message.getAttachment();
        if (TextUtils.isEmpty(attachment.getPath()) && TextUtils.isEmpty(attachment.getThumbPath())) {
            if (message.getAttachStatus() == AttachStatusEnum.fail || message.getStatus() == MsgStatusEnum.fail) {
                imageView.setVisibility(View.VISIBLE);
            } else {
                imageView.setVisibility(View.GONE);
            }
        }
//        if (message.getStatus() == MsgStatusEnum.sending
//                || (message.getAttachStatus() == AttachStatusEnum.transferring)) {
//            float progress = getProgress(message);
//            if (progress==1){
//                progressLayout.setVisibility(View.GONE);
//            }else {
//                progressLayout.setVisibility(View.VISIBLE);
//                String prog = String.format(Locale.US, "%d%%", (int) (progress * 100));
//                progressText.setText(prog);
//            }
//        } else {
//            progressLayout.setVisibility(View.GONE);
//        }
    }


    public void notifyDataItemChanged(int dataIndex) {
        this.notifyItemChanged(dataIndex+1);
    }
    public void putProgress(IMMessage message, float progress){
        progresses.put(message.getUuid(),progress);
    }

    private float getProgress(IMMessage message){
        Float progress = progresses.get(message.getUuid());
        float percent = progress == null ? 0 : progress;
        return percent;
    }

    private void loadUserHeader(String url, ImageView imageView){
        RequestOptions options = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE);
        RequestBuilder builder = Glide.with(mContext).asBitmap()
                .apply(options)
                .load(url).placeholder(R.mipmap.ic_role_head);
        builder.into(imageView);
    }

    private void loadImage(String url,ImageView imageView){
        Glide.with(imageView)
                .load(url)
                .thumbnail(Glide.with(imageView.getContext()).load(R.drawable.nim_loading))
                .fallback(R.mipmap.ic_no_img)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .fitCenter()
                .centerCrop()
                .into(imageView);
    }

    private void userHeaderInEvent(CircleImageView imageView){
        imageView.setOnClickListener(v->adapterEvent.toVisitorInfoActivity());
    }
    //endregion

    //region 接收的房源信息
    class HouseInfoInHolder extends RecyclerView.ViewHolder{

        HouseInfoInHolder(@NonNull View itemView) {
            super(itemView);
            DataBindingUtil.bind(itemView);
        }
    }

    private void bindHouseInfoInHolder(HouseInfoInHolder holder,int position){
        IMMessage message = items.get(position);
        HouseInfoMessage infoMessage = JSON.parseObject(message.getAttachStr()).toJavaObject(HouseInfoMessage.class);
        AdapterImMsgInHouseInfoBinding binding = DataBindingUtil.getBinding(holder.itemView);
        String fromAccount = message.getFromAccount();
        NimUserInfo info = NimUserInfoCache.getInstance().getUserInfo(fromAccount);
        if (info!=null){
            loadUserHeader(info.getAvatar(),binding.imageView);
        }
        userHeaderInEvent(binding.imageView);
        HouseInfoMessage.HouseInfo data = infoMessage.getData();
        if (data!=null){
            binding.titleTextView.setText(data.getTitle());
            binding.subTitleTextView.setText(data.getSubTitle());
            binding.messageLayout.setOnClickListener(v -> adapterEvent.toHouseInfoActivity(data.getHouseCode()));
        }

        showTime(position,binding.msgTimeTextView);
    }

    //endregion

    //region 发送的房源消息
    class HouseInfoOutHolder extends RecyclerView.ViewHolder{

        HouseInfoOutHolder(@NonNull View itemView) {
            super(itemView);
            DataBindingUtil.bind(itemView);
        }
    }

    private void bindHouseInfoOutHolder(HouseInfoOutHolder holder,int position){
        AdapterImMsgOutHouseInfoBinding binding = DataBindingUtil.getBinding(holder.itemView);
        IMMessage message = items.get(position);
        HouseInfoMessage infoMessage = JSON.parseObject(message.getAttachStr()).toJavaObject(HouseInfoMessage.class);
        loadUserHeader(localUser.getAvatar(),binding.imageView);
        HouseInfoMessage.HouseInfo data = infoMessage.getData();
        if (data!=null){
            binding.titleTextView.setText(data.getTitle());
            binding.subTitleTextView.setText(data.getSubTitle());
            binding.messageLayout.setOnClickListener(v -> adapterEvent.toHouseInfoActivity(data.getHouseCode()));
        }
        showTime(position,binding.msgTimeTextView);
    }
    //endregion

    //region 房源信息头部
    class ChartHouseInfoHolder extends RecyclerView.ViewHolder{

        ChartHouseInfoHolder(@NonNull View itemView) {
            super(itemView);
            DataBindingUtil.bind(itemView);
        }
    }

    private void bindChartHouseInfoHolder(ChartHouseInfoHolder holder, int position){
        AdapterImTopHouseInfoBinding binding = DataBindingUtil.getBinding(holder.itemView);
        IMMessage message = items.get(position);
        LocalHouseInfoMessage localHouseInfoMessage = (LocalHouseInfoMessage) message.getAttachment();

        binding.tipTextView.setText(Html.fromHtml(localHouseInfoMessage.getShowAddress()));
        binding.tipTextView.setOnClickListener(v->{
            adapterEvent.onSendHouseInfo(localHouseInfoMessage.getAddress(), localHouseInfoMessage.getCode());
        });
    }

    //endregion

    //加载UI
    class LoadHolder extends RecyclerView.ViewHolder{

        LoadHolder(@NonNull View itemView) {
            super(itemView);
            DataBindingUtil.bind(itemView);
        }
    }

    private OnAdapterEvent adapterEvent;

    public void setAdapterEvent(OnAdapterEvent adapterEvent) {
        this.adapterEvent = adapterEvent;
    }

    public interface OnAdapterEvent{
        /**
         * 查看图片
         * @param imgs
         * @param position
         */
        void onClickPictureItem(ArrayList<ImageViewBean> imgs, int position);

        /**
         * 发送房源信息
         * @param
         */
        void onSendHouseInfo(String houseInfo,String code);

        void toHouseInfoActivity(String houseCode);

        void toVisitorInfoActivity();
    }

    private void baseMessageView(IMMessage message){
        NimIMUtils.sendMessageRe(message.getSessionId(),message);
    }
}
